<template>
  <div class="video-play-ptz-container">
    <div class="header">
      <el-icon
        @click="handGongge"
        class="left-icon"
        style="font-size: 25px; font-weight: bold"
        ><ArrowLeft
      /></el-icon>
      <span class="headerLeft">视频预览</span>
      <!-- <div class="headerRight" @click="handGongge">
        <span>切换宫格</span>
        <img src="@/assets/images/xgjd/gongge.png" alt="" />
      </div> -->
    </div>
    <div
      class="video-box"
      :style="{ height: videoBoxHeight }"
      @click="toggleControls"
    >
      <div v-if="showPlaceholder" class="no-video" @click="handleClick">
        <el-icon class="no-video-icon"><Plus /></el-icon>
        <p>暂无视频流</p>
      </div>
      <videoPlayer
        v-else
        :vid="currentIndexCode"
        ref="videoPlayerRef"
        @capImg="handleCapImg"
        :resolution="resolution"
        :isLandscape="isLandscape"
      />
      <div
        class="centenBtn"
        v-if="(showControls || isLandscape) && !showPlaceholder"
      >
        <img
          src="@/assets/images/xgjd/close.png"
          alt="关闭"
          @click="closeVideo"
        />
        <img
          src="@/assets/images/xgjd/screenshot.png"
          alt="横屏"
          @click="handleScreenRotation"
        />
      </div>
    </div>
    <div class="btnBox" v-if="!isPtzVisible">
      <!-- 声音控制 -->
      <div>
        <div v-if="!isAudioOn" @click="toggleSound" class="btn">
          <img src="@/assets/images/xgjd/closeSound.png" alt="" />
          <span>开启声音</span>
        </div>
        <div v-else @click="toggleSound" class="btn">
          <img src="@/assets/images/xgjd/openSound.png" alt="" />
          <span>关闭声音</span>
        </div>
      </div>

      <!-- 抓拍 -->
      <div>
        <div @click="capturePicture" class="btn">
          <img src="@/assets/images/xgjd/clapPic.png" alt="" />
          <span>抓拍</span>
        </div>
      </div>

      <!-- 云台控制显示切换 funcType==2的时候才显示云台控制按钮 -->
      <!--  -->
      <div v-if="cameradetail.funcType === '2'">
        <div @click="togglePtzPanel" class="btn">
          <img src="@/assets/images/xgjd/yuntai2.png" alt="" />
          <span>云台</span>
        </div>
      </div>

      <!-- 对讲 -->
      <div>
        <div v-if="!isTalking" @click.stop="startTalk" class="btn" id="startTalk">
          <img src="@/assets/images/xgjd/duijiang.png" alt="" />
          <span>对讲</span>
        </div>
        <div v-else @click.stop="stopTalk" class="btn">
          <img src="@/assets/images/xgjd/duijiang.png" alt="" />
          <span>结束对讲</span>
        </div>
      </div>

      <!-- 录像 -->
      <div>
        <div v-if="!isRecording" @click="startRecord" class="btn">
          <img src="@/assets/images/xgjd/video.png" alt="" />
          <span>录像</span>
        </div>
        <div v-else @click="stopRecord" class="btn">
          <img src="@/assets/images/xgjd/overVideo.png" alt="" />
          <span>结束录像</span>
        </div>
      </div>

      <!-- 分辨率切换 -->
      <div>
        <el-dropdown placement="bottom-end" @command="handleResolutionChange">
          <el-button size="mini" class="resolution-btn">
            {{ currentResolution }}
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="1">标清</el-dropdown-item>
              <el-dropdown-item command="0">高清</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="allPanel" v-if="isPtzVisible">
      <div class="panel-title">
        <span>云台控制</span>
        <el-icon @click="togglePtzPanel"><Close /></el-icon>
      </div>
      <div class="panel-box">
        <div class="ptz">
          <ptz width="261" height="261" :did="currentIndexCode"></ptz>
        </div>
        <div class="zoomptz">
          <div
            class="zoombtn"
            @touchstart="handleTouchStart('ZOOM_IN')"
            @touchend="handleTouchEnd"
            @pointerup="handleTouchEnd"
          >
            <img src="@/assets/images/xgjd/zommout.png" />
          </div>
          <div
            class="zoombtn"
            @touchstart="handleTouchStart('ZOOM_OUT')"
            @touchend="handleTouchEnd"
            @pointerup="handleTouchEnd"
          >
            <img src="@/assets/images/xgjd/zoomin.png" />
          </div>
        </div>
      </div>
      <div class="list-yz" v-if="ylist.length > 0">
        <div
          class="listbtn"
          :class="{ active: currentPoint == item.value }"
          v-for="item in ylist"
          :key="item.value"
        >
          <span @click="setYzd(item)"> {{ item.label }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { getPointUrl, getPointUrlBack, talkToseppk } from "@/api/event.js";
import { onMounted, ref } from "vue";
import videoPlayer from "@/components/video/videobf.vue";
import { nextTick } from "vue"; // 需导入 nextTick
import ptz from "@/components/ptz.vue";
import { useRoute, useRouter } from "vue-router";
import { handlecameracontrol, getcameradetail } from "@/api/videoplan.js";
import { tr } from "element-plus/es/locale/index.mjs";
const route = useRoute();
let currentIndexCode = ref("");
const currentResolution = ref("标清"); // 当前清晰度
const resolution = ref("1"); //组件传值定义分辨率参数，默认标清（1）
const videoPlayerRef = ref(null);
const isAudioOn = ref(false); // 声音状态
const isRecording = ref(false); // 录像状态
const isTalking = ref(false); // 对讲状态
const isPtzVisible = ref(false); // 云台面板显示状态
const router = useRouter();
const ylist = ref([
  {
    label: "预置点1",
    value: "1",
  },
  {
    label: "预置点2",
    value: "2",
  },
  {
    label: "预置点3",
    value: "3",
  },
  {
    label: "预置点4",
    value: "4",
  },
]);

let cameradetail = ref({}); // 设备详情
let currentPoint = ref({});
// 原始的transId---从缓存中取
const transId = ref("");
// 全屏的高度 动态显示
const videoBoxHeight = ref("217px");
const videoBoxWidth = ref("100%"); // 默认初始值
// 新增的响应式变量
const showControls = ref(false); // 控制按钮是否显示
const showPlaceholder = ref(false); // 是否显示占位符
const isLandscape = ref(false); // 是否横屏
// 点击视频出现按钮
const toggleControls = async () => {
  console.log("ssssssssssssssssss", showPlaceholder.value);

  if (!showPlaceholder.value) {
    showControls.value = !showControls.value;
    // 3秒后自动隐藏控制按钮
    if (showControls.value) {
      setTimeout(() => {
        showControls.value = false;
      }, 3000);
    }
  }
};
// 点击出现视频流
const handleClick = async () => {
  console.log("点击出现视频流");
  // 如果点击占位符，重新加载视频
  showPlaceholder.value = false;
  console.log("重新加载视频");
  await nextTick();
  // 调用子组件的加载视频方法
  if (
    videoPlayerRef.value &&
    typeof videoPlayerRef.value.loadVideo === "function"
  ) {
    try {
      await videoPlayerRef.value.loadVideo();
      console.log("视频重新加载成功");
    } catch (err) {
      console.error("视频加载失败:", err);
      ElMessage.error("视频加载失败，请重试");
      showPlaceholder.value = true; // 加载失败重新显示占位符
    }
  } else {
    console.error("子组件加载方法未定义");
    ElMessage.error("视频组件初始化失败");
  }
};
// 关闭视频
const closeVideo = async () => {
  if (videoPlayerRef.value) {
    videoPlayerRef.value.pause();
  }

  showPlaceholder.value = true;
  showControls.value = false;
  await nextTick(); // 等待 DOM 渲染完成
  console.log(
    "关闭视频",
    showPlaceholder.value,
    showControls.value,
    isLandscape.value
  );
};
// 判断是不是ipad
const isIpad = () => {
  // navigator.userAgent.toLowerCase() 判断当前用户所使用的浏览器
  const ua = navigator.userAgent.toLowerCase();
  return (
    // 检测当前窗口的宽度是否在 768px 到 1024px 之间
    /ipad/.test(ua) || (window.innerWidth >= 768 && window.innerWidth <= 1024)
  );
};

// 横屏处理
const handleScreenRotation = () => {
  isLandscape.value = !isLandscape.value;
  console.log("横屏状态切换:", isLandscape.value);
  // 切换全屏类名
  if (isLandscape.value) {
    document.documentElement.classList.add("video-fullscreen");
    videoBoxHeight.value = "100vh";
    videoPlayerRef.value.resize();
  } else {
    document.documentElement.classList.remove("video-fullscreen");
    videoBoxHeight.value = isIpad() ? "35vh" : "232px";
    videoPlayerRef.value.resize();
  }
};
// 跳转宫格页面
const handGongge = () => {
  console.log("跳转宫格页面", transId.value);
  router.push({
    name: "videoIndex",
    query: {
      transId: transId.value,
      type: "gongge",
    },
  });
};
const handleTouchStart = (cmd) => {
  handlecameracontrol({
    action: 0,
    cameraId: currentIndexCode.value,
    command: cmd,
  });
};
const handleTouchEnd = (e) => {
  e.preventDefault();
  setTimeout(() => {
    handlecameracontrol({
      action: 1,
      cameraId: currentIndexCode.value,
      command: "LEFT",
    });
  }, 30);
};

// 1. 声音控制
const toggleSound = async () => {
  console.log("声音控制", isAudioOn.value);
  try {
    if (isAudioOn.value) {
      await videoPlayerRef.value.turnOffSound();
    } else {
      await videoPlayerRef.value.turnOnSound();
    }
    isAudioOn.value = !isAudioOn.value;
  } catch (err) {
    console.error(`声音控制失败: ${err.message}`);
  }
};

// 2. 抓拍
const capturePicture = async () => {
  try {
    await videoPlayerRef.value.toCapImg();
  } catch (err) {
    console.error(`抓拍失败: ${err.message}`);
  }
};

const handleCapImg = (imageUrl) => {
  const a = document.createElement("a");
  a.href = imageUrl;
  a.download = `capture_${Date.now()}.jpeg`;
  a.click();
  URL.revokeObjectURL(imageUrl);
};

// 3. 云台面板显示切换
const togglePtzPanel = () => {
  isPtzVisible.value = !isPtzVisible.value;
};

// 4. 对讲控制
const startTalk = async (e) => {
  console.log("开始对讲 - 函数被调用", e, videoPlayerRef.value);
  try {
    // 1. 获取当前设备ID
    const deviceId = currentIndexCode.value;
    if (!deviceId) {
      throw new Error("未选择设备");
    }

    // 2. 从后端获取对讲地址
    const { data } = await talkToseppk({ deviceId });
    const talkUrl = data.url; // 假设返回格式包含talkUrl字段

    if (!talkUrl) {
      throw new Error("获取对讲地址失败");
    }

    // 3. 调用子组件的startTalk方法并传入对讲地址（底层插件会自动处理权限请求）
    await videoPlayerRef.value.startTalk(talkUrl);
    isTalking.value = true;
    console.log("开始对讲成功---");
  } catch (err) {
    // 错误已在 videobf.vue 中处理，这里只打印到控制台
    const errorMessage = err?.message || err?.toString() || "未知错误";
    console.error("对讲启动失败:", errorMessage, err);
  }
};

const stopTalk = async () => {
  try {
    // 直接调用子组件的stopTalk方法
    await videoPlayerRef.value.stopTalk();
    isTalking.value = false;
    console.log("结束对讲成功");
  } catch (err) {
    console.error(`对讲停止失败: ${err.message}`);
  }
};

// 5. 录像控制
const startRecord = async () => {
  try {
    const fileName = `record_${Date.now()}`; // 唯一文件名
    await videoPlayerRef.value.startRecording();
    isRecording.value = true;
    console.log("开始录像");
  } catch (err) {
    console.error(`录像启动失败: ${err.message}`);
  }
};

const stopRecord = async () => {
  try {
    await videoPlayerRef.value.stopRecording();
    isRecording.value = false;
    console.log("录像已保存");
  } catch (err) {
    console.error(`录像停止失败: ${err.message}`);
  }
};

// 6. 分辨率切换（需重新取流）
const handleResolutionChange = async (value) => {
  console.log("分辨率切换", value);
  currentResolution.value = value === "1" ? "标清" : "高清";
  resolution.value = value; // 更新分辨率参数，会自动传递给子组件
};

// 预制点设置
const setYzd = (item) => {
  currentPoint.value = item.value;
  // 调用云台控制接口跳转到指定预制点
  handlecameracontrol({
    action: 0,
    cameraId: currentIndexCode.value,
    command: "GOTO_PRESET",
    presetIndex: item.value,
  });
};

// 初始化
onMounted(async () => {
  currentIndexCode.value = route.query.indexCode;
  console.log("currentIndexCode写带过来的原始id", currentIndexCode.value);
  console.log(
    'localStorage.getItem("transId")',
    localStorage.getItem("transId")
  );
  transId.value = localStorage.getItem("transId");

  let res = await getcameradetail({
    deviceId: currentIndexCode.value,
  });
  cameradetail.value = res.data;
  videoBoxHeight.value = isIpad() ? "35vh" : "232px";
  videoPlayerRef.value.resize();
  document.documentElement.classList.remove("video-fullscreen");
  
  // 调试：检查对讲按钮是否存在
  setTimeout(() => {
    const startTalkBtn = document.getElementById("startTalk");
    console.log("对讲按钮元素:", startTalkBtn);
    console.log("isTalking状态:", isTalking.value);
    if (startTalkBtn) {
      console.log("对讲按钮已找到，添加测试点击");
      startTalkBtn.addEventListener("click", (e) => {
        console.log("原生事件监听器触发", e);
      });
    } else {
      console.warn("对讲按钮未找到！");
    }
  }, 1000);
});
</script>

<style lang="scss" scoped>
.video-play-ptz-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #f4f6fa;
  padding-top: 20px;
  .header {
    width: 100%;
    height: 100rpx;
    margin-top: 50rpx;
    background: #fff;
    text-align: center;
    line-height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .left-icon {
      position: absolute;
      left: 2%;
      cursor: pointer;
      :deep(.el-icon) {
        font-size: 20px;
        font-weight: bold;
      }
    }
    .headerLeft {
      flex: 1;
      text-align: center;
      // margin-left: 10px;
    }
    .headerRight {
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #333333;
      text-align: right;
      font-style: normal;
      position: absolute;
      right: 0;
      img {
        width: 25px;
        height: 25px;
      }
    }
  }
  .video-box {
    margin-top: 28rpx;
    width: 100%;
    height: 434rpx;
    overflow: hidden;
    padding: 0 28rpx;
    position: relative;

    .no-video {
      position: absolute;
      top: 0%;
      left: 0;
      width: 92%;
      height: 90%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #999;
      background: #5f5f5f;
      z-index: 100;
      margin: 0 28rpx;
    }
    ::v-deep(.video-fullscreen &) {
      padding: 0 !important; // 移除内边距，避免左右留白
      margin-top: 0 !important; // 移除顶部间距
      height: 100vh !important; // 占满整个视口高度
    }

    .centenBtn {
      position: absolute;
      bottom: 0%;
      left: 0;
      right: 0;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      gap: 250px;
      background: #1c1b1b;
      color: white;
      z-index: 9999;
      padding: 0 28rpx;
      margin: 0 30rpx;
      height: 30px;
      img {
        width: 24px;
        height: 24px;
        cursor: pointer;
      }
    }
  }

  .point-info {
    width: calc(100% - 56rpx);
    margin: 0 auto;
    height: 134rpx;
    background: #fff;
    padding: 15rpx 38rpx;
    // padding: 0 28rpx;

    .name-info {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .name {
        margin-top: 17rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 23rpx;
        color: #333333;
        line-height: 33rpx;
      }

      .lineStatus {
        margin-top: 10rpx;
        display: flex;
        align-items: center;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 23rpx;
        color: #39aa92;
        line-height: 33rpx;

        .circle {
          width: 17rpx;
          height: 17rpx;
          border-radius: 50%;
          background: #39aa92;
          margin-right: 10rpx;
        }
      }
    }

    .types {
      margin-top: 10rpx;
      display: flex;
      align-items: center;

      .tip {
        min-width: 81rpx;
        height: 38rpx;
        background: #d2f0ff;
        border-radius: 8rpx;
        text-align: center;
        padding: 0 17rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 23rpx;
        color: #45aff7;
        line-height: 38rpx;
      }
    }
  }

  .panel-title {
    padding: 10px 28rpx 0 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      flex: 1;
      text-align: center;
    }
    .el-icon {
      color: #999999;
      font-size: 20px;
    }
  }
  .panel-box {
    margin-top: 26rpx;
    display: flex;
    align-items: top;
    padding: 0 28rpx;

    .ptz {
      padding: 38rpx 98rpx 36rpx 84rpx;
      width: 444rpx;
      height: 337rpx;
      background: #ffffff;
      box-shadow: 0rpx 0rpx 56rpx 0rpx rgba(70, 102, 149, 0.06);
      margin-right: 19rpx;
    }
    .zoomptz {
      width: 229rpx;
      height: 337rpx;
      background: #ffffff;
      box-shadow: 0rpx 0rpx 56rpx 0rpx rgba(70, 102, 149, 0.06);
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding-left: 90rpx;
      .zoombtn {
        width: 76rpx;
        height: 76rpx;
        background: #e4effd;
        border-radius: 15rpx;
        border: 2rpx solid #c3dcff;
        padding: 17rpx;
        image {
          width: 42rpx;
          height: 42rpx;
        }
      }
    }
  }
  .tips {
    text-align: center;
    opacity: 0.5;
    margin-top: 100rpx;
  }
}
.list-yz {
  background: #ffffff;
  box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
  height: 120px;
  width: auto; /* 取消固定宽度限制，让容器自适应内容 */
  overflow: auto;
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 从左侧开始排列 */
  flex-wrap: wrap; /* 启用自动换行 */
  gap: 10px; /* 按钮之间的间距（水平和垂直方向） */
  margin: 10px 28rpx; /* 与其他区域保持一致的左右内边距 */
  padding: 0 28rpx;
  /* 关键：通过计算每个按钮的宽度实现一行3个 */
  .listbtn {
    width: calc(
      33.33% - 7px
    ); /* 33.33%分配3个，减去gap的影响（10px/3≈3.33，两边各占一半） */
    height: 34px;
    line-height: 34px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #333333;
    text-align: center;
    background: rgba(142, 191, 255, 0.32);
    border-radius: 6px;
    box-sizing: border-box; /* 确保padding和border不影响宽度计算 */

    &.active {
      background: #2263bf;
      font-size: 12px;
      color: #ffffff;
    }
  }
}
.btnBox {
  background: #ffffff;
  box-shadow: 0rpx 0rpx 56rpx 0rpx rgba(70, 102, 149, 0.06);
  height: 150px;
  /* 关键样式：启用flex布局并允许换行 */
  display: flex;
  align-items: center;
  flex-wrap: wrap; /* 超出一行时自动折行 */
  gap: 10rpx; /* 按钮之间的间距（可选，根据需求调整） */
  margin: 0 28rpx; /* 与视频区域保持一致的左右内边距，避免错位 */
  margin-top: 20rpx; /* 与视频区域保持一定距离 */
}

/* 调整每个按钮容器的宽度，确保一行放4个 */
.btnBox > div {
  width: calc(25% - 10rpx); /* 25%宽度分配4个，减去gap的影响 */
  box-sizing: border-box; /* 确保padding和border不影响宽度计算 */
  text-align: center;
}

.btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  /* 图片和文字的间距 */
  img {
    width: 35px;
    height: 35px;
  }
  span {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #333333;
    text-align: right;
    font-style: normal;
  }
}
/* 新增横屏控制按钮样式 */
.landscape-controls {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1001;
  img {
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
}

.video-fullscreen {
  .video-play-ptz-container {
    padding-top: 0px !important;
  }
  .video-box {
    position: relative !important;
    margin: 0 !important;
  }
  .common-layout {
    width: 100vh !important;
    height: 100vw !important;
  }
  .header {
    display: none;
  }
  .speedBox {
    display: none;
  }
  .footer-info {
    display: none;
  }
  .center-info {
    display: none;
  }
}
/* 新增横屏时的按钮定位样式 */
.is-landscape .centenBtn,
.video-fullscreen .centenBtn {
  top: 0% !important;
  left: 0% !important;
  bottom: auto !important;
  width: 60px !important; // 左侧宽度
  height: 100vh !important; // 高度
  flex-direction: column !important;
  gap: 400px !important; // 控制项之间的间距
  position: absolute !important;
  background: #1c1b1b !important;
  z-index: 99999 !important;
  margin: 0 !important;
  padding: 0 !important;
  img {
    transform: rotate(90deg);
    transform-origin: center;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
.video-fullscreen .no-video {
  height: 100% !important;
  width: 100% !important;
  margin: auto;
}
</style>
